package com.zhiwang.planet.mvvm.viewmodel.withdraw

import androidx.lifecycle.LiveData
import androidx.lifecycle.switchMap
import androidx.paging.PagedList
import androidx.paging.toLiveData
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawRecord
import javax.inject.Inject


data class Listing<T>(val pagedList: LiveData<PagedList<T>>,
                      val refreshing: LiveData<PagedList.LoadState>,
                      val loadingMoreState: LiveData<PagedList.LoadState>,
                      val err: LiveData<Throwable>,
                      val initLoadDone: LiveData<Boolean>)

interface DetailRepository {

    fun recordsOfWithDraw(pageSize: Int): Listing<WithDrawRecord>
}

class UserDetailRepository @Inject constructor(val restApi: RestApi) : DetailRepository {


    override fun recordsOfWithDraw(pageSize: Int): Listing<WithDrawRecord> {

        val sourceFactory = WithDrawDataSourceFactory(restApi)

        val pagedList = sourceFactory.toLiveData(
                pageSize = 12,
                initialLoadKey = 0
        )


        val loadingMoreState = sourceFactory.sourceLiveData.switchMap { it.loading }

        val refreshingState = sourceFactory.sourceLiveData.switchMap { it.refreshing }

        val err = sourceFactory.sourceLiveData.switchMap { it.err }
        return Listing(
                pagedList = pagedList,
                refreshing = refreshingState,
                loadingMoreState = loadingMoreState,
                err = err,
                initLoadDone = sourceFactory.sourceLiveData.switchMap { it.initLoadDone }
        )
    }

}